
package com.tools.cleanmaster.ui.card.animator;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PixelFormat;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.FloatEvaluator;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nineoldandroids.animation.ValueAnimator;
import com.tools.cleanmaster.CleanApplication;
import com.tools.cleanmaster.R;
import com.tools.cleanmaster.ui.card.ui.GPlayRatingStar;
import com.tools.cleanmaster.utils.CompatibilityHelper;
import com.tools.cleanmaster.utils.UiUtils;

public class RateRecommendWindow {
    private static final long AUTO_ROMOVE_TIPS_TIME = 2000;
    private static final int CARD_APPEAR_DURATION = 600;
    private static final int HAND_CLICK_DURATION = 500;
    private static final int CIRLE_TIP_DURATION = 500;
    private static final int HAND_MOVE_DURATION = 600;
    private static final int SHOW_TIPSLAYOUT = 1;
    private static final int CLEAN_TIPSLAYOUT = 2;
    private static final int MAX_SHOW_COUNT = 2;

    private static RateRecommendWindow sInstance;

    private Context mAppContext;
    private View mTipsLayout;
    private TextView mTip;

    private ImageView mRateHand;
    private ImageView mRateCircleTip;
    private ImageView mRateTriTip;
    private LinearLayout mRateCard;

    private WindowManager mWindowManager;
    private WindowManager.LayoutParams mParams;

    private boolean mHasRemoved = true;
    private boolean mTipsAdded = false;
    private boolean mHandCycledFlag = false;


    private LayoutInflater mInflater;
    private final String SYSTEM_REASON = "reason";
    private final String SYSTEM_HOME_KEY = "homekey";

    private IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);

    private int tipShowCount = 0;
    /**
     * 监听是否点击了home键将客户端推到后台
     */
    private BroadcastReceiver mHomeKeyEventReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_REASON);
                if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {
                    removeView();
                }
            }
        }
    };

    private Handler myHandler = new Handler(CleanApplication.getInstance().getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SHOW_TIPSLAYOUT:
                    mAppContext.registerReceiver(mHomeKeyEventReceiver, homeFilter);
                    try {
                        if (!mTipsAdded && tipShowCount < MAX_SHOW_COUNT) {
                            tipShowCount++;
                            mTipsAdded = true;

                            mTipsLayout = mInflater.inflate(R.layout.show_rate_windows, null);
                            mTip = mTipsLayout.findViewById(R.id.rating_dialog_2_go_gp_tip);
                            Typeface mediumFont = Typeface.createFromAsset(CleanApplication.getInstance().getAssets(), "fonts/Roboto-Medium.ttf");
                            mTip.setTypeface(mediumFont);
                            mRateHand = mTipsLayout.findViewById(R.id.gp_ratehand);
                            mRateCircleTip = mTipsLayout.findViewById(R.id.gp_ratecircletip);
                            mRateTriTip = mTipsLayout.findViewById(R.id.gp_ratetritip);
                            mRateCard = mTipsLayout.findViewById(R.id.rate_bottom_card);
                            mTip.getPaint().setFakeBoldText(true);
                            final GPlayRatingStar mStarView = mTipsLayout.findViewById(R.id.star);

                            mWindowManager.addView(mTipsLayout, mParams);
                            mStarView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    mStarView.startAnimation();
                                }
                            }, 300);

                            appearAnim(mRateCard);
                            mHandCycledFlag = false;
                            mRateHand.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    handClickAnimation(mRateHand);
                                }
                            }, 400);

                            setIsRemove(false);
                        }

                    } catch (Exception ex) {
                        //部分手机会因为使用TYPE_TOAST而奔溃
                        ex.printStackTrace();
                    }

                    if (!myHandler.hasMessages(CLEAN_TIPSLAYOUT)) {
                        myHandler.sendEmptyMessageDelayed(CLEAN_TIPSLAYOUT, AUTO_ROMOVE_TIPS_TIME);
                    }

                    break;
                case CLEAN_TIPSLAYOUT:
                    if (mTipsLayout != null) {
                        if (mTipsAdded) {
                            mTipsAdded = false;
                            if (mTipsLayout.getParent() != null) {
                                try {
                                    mWindowManager.removeView(mTipsLayout);
                                } catch (Exception e) {
                                }
                            }
                            mTipsLayout = null;
                        }
                    }
                    if (mHomeKeyEventReceiver != null) {
                        CleanApplication.getInstance().unregisterReceiver(mHomeKeyEventReceiver);
                        mHomeKeyEventReceiver = null;
                    }

                    if (mRateHand != null) {
                        mRateHand.clearAnimation();
                    }
                    if (mRateCircleTip != null) {
                        mRateCircleTip.clearAnimation();
                    }
                    if (mRateTriTip != null) {
                        mRateTriTip.clearAnimation();
                    }
                    break;
            }
        }
    };

    private RateRecommendWindow() {
        mAppContext = CleanApplication.getInstance();
        mWindowManager = (WindowManager) mAppContext.getSystemService(Context.WINDOW_SERVICE);
        mParams = new WindowManager.LayoutParams();
        mParams.type = (Build.VERSION.SDK_INT >= 23) ? WindowManager.LayoutParams.TYPE_PHONE : WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        mParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        mParams.height = WindowManager.LayoutParams.MATCH_PARENT;
        mParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
        mParams.format = PixelFormat.RGBA_8888;
        mInflater = (LayoutInflater) mAppContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public static RateRecommendWindow getsInstance() {
        synchronized (RateRecommendWindow.class) {
            if (sInstance == null) {
                sInstance = new RateRecommendWindow();
            }
        }
        return sInstance;
    }

    public void addView() {
        myHandler.sendEmptyMessageDelayed(SHOW_TIPSLAYOUT, 400);
    }

    public void removeView() {
        if (!mHasRemoved) {
            myHandler.sendEmptyMessage(CLEAN_TIPSLAYOUT);
            setIsRemove(true);
        }
    }

    public void forciblyRemoveView() {
        myHandler.sendEmptyMessage(CLEAN_TIPSLAYOUT);
    }

    private void setIsRemove(boolean remove) {
        mHasRemoved = remove;
    }

    private void appearAnim(View cardView) {
        ObjectAnimator alpha = ObjectAnimator.ofFloat(cardView, "alpha", 0.0f, 1.0f);
        AnimatorSet set = new AnimatorSet();
        set.playTogether(alpha);
        set.setDuration(CARD_APPEAR_DURATION);
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animator) {
            }
        });
        set.start();
    }

    private void handClickAnimation(final View handView) {
        handView.setVisibility(View.VISIBLE);
        ObjectAnimator translationY = ObjectAnimator.ofFloat(handView, "translationY", 0, 3);
        ObjectAnimator rotationX = ObjectAnimator.ofFloat(handView, "rotationX", 0f, 10f);
        ObjectAnimator rotationY = ObjectAnimator.ofFloat(handView, "rotationY", 0f, -10f);
        AnimatorSet set = new AnimatorSet();
        set.playTogether(translationY, rotationX, rotationY);
        set.setDuration(HAND_CLICK_DURATION);
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animator) {
                mRateCircleTip.setVisibility(View.VISIBLE);
                mRateTriTip.setVisibility(View.VISIBLE);
                handView.clearAnimation();
                tipAnimation(mRateCircleTip);
            }
        });
        set.start();
    }

    @SuppressLint("NewApi")
    private void tipAnimation(final View cTipView) {
        ObjectAnimator alpha = ObjectAnimator.ofFloat(cTipView, "alpha", 1.0f, 0.0f);
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(cTipView, "scaleX", 1.0f, 1.5f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(cTipView, "scaleY", 1.0f, 1.5f);
        if (CompatibilityHelper.isHigherAndroid3_0()) {
            cTipView.setPivotX(cTipView.getWidth() >> 2);
            cTipView.setPivotY(cTipView.getHeight() >> 2);
        }
        AnimatorSet set = new AnimatorSet();
        set.playTogether(alpha, scaleX, scaleY);
        set.setDuration(CIRLE_TIP_DURATION);
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animator) {
                cTipView.clearAnimation();
                handMoveAnimation(mRateHand, mRateTriTip);
            }
        });
        set.start();
    }

    private void handMoveAnimation(final View mHand, final View mTipView) {
        @SuppressWarnings("deprecation")
        int padding = UiUtils.dipToPx(200);
        int height = mWindowManager.getDefaultDisplay().getHeight() - padding;
        ObjectAnimator handAlpha = ObjectAnimator.ofFloat(mHand, "alpha", 1.0f, 0.0f);
        ValueAnimator translateY = ObjectAnimator.ofObject(mHand, "translationY", new FloatEvaluator(), 0, -height);

        ObjectAnimator tipAlpha = ObjectAnimator.ofFloat(mTipView, "alpha", 1.0f, 0.0f);
        ValueAnimator tipTransY = ObjectAnimator.ofObject(mTipView, "translationY", new FloatEvaluator(), 0, -height / 2);
        tipAlpha.setDuration(HAND_MOVE_DURATION / 2);
        tipTransY.setDuration(HAND_MOVE_DURATION / 2);
        handAlpha.setDuration(HAND_MOVE_DURATION);
        translateY.setDuration(HAND_MOVE_DURATION);
        AnimatorSet set = new AnimatorSet();
        set.playTogether(handAlpha, translateY, tipAlpha, tipTransY);
        set.start();
        set.addListener(new AnimatorListenerAdapter() {
            @SuppressLint("NewApi")
            @Override
            public void onAnimationEnd(Animator animator) {
                if (CompatibilityHelper.isHigherAndroid3_0()) {
                    mHand.clearAnimation();
                    mTipView.clearAnimation();
                    if (!mHandCycledFlag) {
                        mHand.setAlpha(1);
                        handClickAnimation(mRateHand);
                        mHandCycledFlag = true;
                    }
                }
            }
        });
    }
}